package com.moweilin.folded_binding;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by moweilin on 2017/1/23.
 */
public class PDDocumentBuilder {
    private PDDocument document;
    private Integer pageCount;
    private List<Integer> indexList;

    public PDDocumentBuilder(PDDocument document) {
        this.document = document;
        this.indexList = new ArrayList<>();
        pageCount = document.getNumberOfPages();
        for (int i = 0; i < pageCount; i++) {
            indexList.add(i);
        }
    }
    public static PDDocumentBuilder create(String file){
        try {
            return new PDDocumentBuilder(PDDocument.load(new File(file)));
        } catch (IOException e) {
            throw  new RuntimeException(e);
        }
    }
    public static PDDocumentBuilder create(PDDocument document){
        return new PDDocumentBuilder(document);
    }
    public PDDocumentBuilder insertBlankPage(int index){
        indexList.add(index,Integer.MAX_VALUE);
        return this;
    }
    public PDDocumentBuilder deletePage(int index){
        indexList.remove(index);
        return this;
    }

    public PDDocumentBuilder moveTo(int from, int to){
        int fromIndex = indexList.get(from);
        indexList.remove(from);
        indexList.add(to,fromIndex);
        return this;
    }
    public PDDocumentBuilder moveLastTo(int to){
        moveTo(indexList.size() - 1,to);
        return this;
    }

    public PDDocument build() throws IOException {
        PDDocument newDocument = new PDDocument();
        indexList.forEach(index->{
            PDPage page;
            if(index > pageCount){
                page = new PDPage();
            }else {
                page = document.getPage(index);
            }
            newDocument.addPage(page);
        });

        return newDocument;
    }
}
